package com.cxyd.modules.job.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cxyd.common.constant.Constant;
import com.cxyd.common.constant.ScheduleConstants;
import com.cxyd.common.exception.TaskException;
import com.cxyd.common.page.PageData;
import com.cxyd.common.service.impl.BaseServiceImpl;
import com.cxyd.common.utils.ConvertUtils;
import com.cxyd.modules.job.dao.SysJobDao;
import com.cxyd.modules.job.dto.SysJobDTO;
import com.cxyd.modules.job.entity.SysJobEntity;
import com.cxyd.modules.job.service.SysJobService;
import com.cxyd.modules.job.utils.ScheduleUtils;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysJobServiceImpl extends BaseServiceImpl<SysJobDao, SysJobEntity> implements SysJobService {
    private final Scheduler scheduler;
    private final SysJobDao jobDao;

    public SysJobServiceImpl(Scheduler scheduler, SysJobDao jobDao) {
        this.scheduler = scheduler;
        this.jobDao = jobDao;
    }

    /**
     * 项目启动时，初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理
     * 注：不能手动修改数据库ID和任务组名，否则会导致脏数据
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException {
        scheduler.clear();
        List<SysJobEntity> jobList = jobDao.selectJobAll();
        for (SysJobEntity job : jobList) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    @Override
    public PageData<SysJobDTO> page(Map<String, Object> params) {
        IPage<SysJobEntity> page = baseDao.selectPage(
                getPage(params, Constant.CREATE_DATE, false),
                getWrapper(params)
        );
        return getPageData(page, SysJobDTO.class);
    }

    @Override
    public SysJobDTO get(Long id) {
        SysJobEntity entity = baseDao.selectById(id);
        return ConvertUtils.sourceToTarget(entity, SysJobDTO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysJobDTO dto) {
        SysJobEntity job = ConvertUtils.sourceToTarget(dto, SysJobEntity.class);
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = baseDao.insert(job);
        if (rows > 0) {
            try {
                ScheduleUtils.createScheduleJob(scheduler, job);
            } catch (SchedulerException e) {
                e.printStackTrace();
            } catch (TaskException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysJobDTO dto) {
        SysJobEntity job = ConvertUtils.sourceToTarget(dto, SysJobEntity.class);
        this.updateById(job);
        //判断job是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(job.getJobId(), job.getJobGroup());
        try {
            if (scheduler.checkExists(jobKey)) {
                scheduler.deleteJob(jobKey);
            }
            ScheduleUtils.createScheduleJob(scheduler, job);
        } catch (SchedulerException e) {
            e.printStackTrace();
        } catch (TaskException e) {
            e.printStackTrace();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            try {
                scheduler.deleteJob(ScheduleUtils.getJobKey(id, "DEFAULT"));
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
        //删除数据
        this.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public int updateBatch(Long[] ids, int status) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("ids", ids);
        map.put("status", status);
        return baseDao.updateBatch(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pause(Long[] ids) {
        for (Long id : ids) {
            try {
                scheduler.pauseJob(ScheduleUtils.getJobKey(id, "DEFAULT"));
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
        updateBatch(ids, Constant.ScheduleStatus.PAUSE.getValue());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resume(Long[] ids) {
        for (Long id : ids) {
            try {
                scheduler.resumeJob(ScheduleUtils.getJobKey(id, "DEFAULT"));
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
        updateBatch(ids, Constant.ScheduleStatus.NORMAL.getValue());
    }

    private QueryWrapper<SysJobEntity> getWrapper(Map<String, Object> params) {
        return null;
    }

    @Override
    public boolean checkCronExpressionIsValid(String cronExpression) {
        return false;
    }
}
